#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <string>

int main()
{
  FILE *pFile;
  //pFile = fopen("test_fopen_file.txt", "w");
  pFile = fopen("test_fopen_file.txt", "r");
  int errsv;
  if (pFile != NULL)
  {
#if 0
    //part1: use fputs to write C string to file.
    errno = 0;
    if(fputs ("This is the test_fopen_file.txt\n", pFile) < 0)
    //if(fputs ("Should not read me!\n", pFile) < 0)
    {
      //value of errno should be saved before other call, like printf();
      errsv = errno;
      printf("fputs() failed. %s\n", strerror(errsv));
    }
    //ferror - check stream status
    if(ferror(pFile))
    {
      printf("Error writing to file.\n");
    }
#endif

#if 1
    //part2: use fwrite to write block of data to file
    std::string str ("Today is a sunny day.\nEveryone is happy.\n");
    errno = 0;
    printf("errno = %d\n", errno);
    fwrite(str.c_str(), 1, str.length(), pFile);
    //value of errno should be saved before other call, like printf();
    errsv = errno;
    printf("errno = %d\n", errno);
    if(ferror(pFile))
    {
      //value of errno should be saved before other call, like printf();
      //errsv = errno;
      printf("fwrite() failed. %s\n", strerror(errsv));
    }
#endif
    if(ferror(pFile))
    {
      printf("1. ferror != 0\n");
    }

    clearerr(pFile);

    if(ferror(pFile))
    {
      printf("2. ferror != 0\n");
    }

    fclose(pFile);
  }
  else
  {
    //perror - print a system error message
    errsv = errno;
    printf("fopen() failed. %s\n", strerror(errsv));
    perror ("Error opening file");
    //printf("please change file mode.\n");
  } 

  return 0;
}
